﻿using Grpc.Core;
using GRPCClass;
using SdtpsNodeLibrary;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace GRPCServer
{
    public class GRPCServer
    {
        public static int Port = 9007;
        public static string Ipadd = "";
        public static System.Windows.Forms.Control viewctrl;
        /// <summary>
        /// 停止后台的线程执行
        /// </summary>
        /// <returns></returns>
        public static string StopServer()
        {
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["centerhandleip"]))
            {
                NodeHandle.IsStop = true;
                return "停止执行节点";
            }
            if (myc != null)
            {
                myc.isStop = true;
                return "停止控制节点";
            }
            return "";
        }
        static SdtpsLibrary.CenterWorker myc;
        /// <summary>
        /// 启动服务
        /// </summary>
        public static string StartServer()
        {
            Port = SdtpsBase.Util.StrToInt(ConfigurationManager.AppSettings["nodeport"].ToString());
            Server server = new Server
            {
                Services = { gRPC.BindService(new gRPCImpl()) },
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };
            string ipadd = "";
            IPAddress[] ipArray;
            ipArray = Dns.GetHostAddresses(Dns.GetHostName());
            for (int i = 0; i < ipArray.Length; i++)
            {
                if (!ipArray[i].IsIPv6LinkLocal)
                {
                    server.Ports.Add(new ServerPort(ipArray[i].ToString(), Port, ServerCredentials.Insecure));
                    ipadd = ipArray[i].ToString();
                }
            }
            server.Start();
            Ipadd = ipadd;
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["centerhandleip"]))
            { 
                string msg = NodeHandle.Start();
                if (viewctrl != null)
                {
                    viewctrl.Invoke(new EventHandler(Show_Text), msg);
                } 
            }

            myc = new SdtpsLibrary.CenterWorker();
            myc.Start();

            return string.Format("{0}:{1}", ipadd, Port);
        }
        public static void Show_Text(object sender, EventArgs e)
        {
            viewctrl.Text += string.Format("{0}\t{1}\r\n",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),sender.ToString());
        }

    }
}
